package org.groupg.practice;

import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * CSV文件读取工具类
 */
public class CsvReaderUtil {
    private static final Logger logger = LoggerFactory.getLogger(CsvReaderUtil.class);

    /**
     * 读取CSV文件
     * @param filePath 文件路径
     * @param separator 字段分隔符
     * @param skipLines 跳过的行数（如标题行）
     * @return 解析后的对象列表
     */
    public static <T> List<T> readCsv(String filePath, char separator, int skipLines, Class<T> type) {
        try (Reader reader = Files.newBufferedReader(Paths.get(filePath))) {
            logger.info("开始读取CSV文件: {}", filePath);

            // 配置列名映射策略
            HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
            strategy.setType(type);

            // 构建CSV解析器
            CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(reader)
                .withMappingStrategy(strategy)
                .withSeparator(separator)
                .withSkipLines(skipLines)
                .withIgnoreLeadingWhiteSpace(true)
                .build();

            // 解析数据
            List<T> result = csvToBean.parse();

            logger.info("成功从 {} 读取 {} 条记录", filePath, result.size());
            return result;
        } catch (Exception e) {
            logger.error("读取CSV文件失败: {}", filePath, e);
            throw new CsvOperationException("CSV读取失败", e);
        }
    }
}